<template>
    <div class="app-container" ref="appContainer">
  
      <el-tabs v-model="activeName" @tab-click="onClickTab"  >
        <el-tab-pane label="账号列表" name="first">
          
          <div class="header">
        <el-form :inline="true" class="search-form" :model="inputSearch" ref="ruleFormRef">
          <el-form-item label="账号:">
            <el-input v-model="inputSearch.account" :placeholder="`请输入账号`" clearable />
        </el-form-item>
        <el-form-item label="IP:">
            <el-input v-model="inputSearch.ip" :placeholder="`请输入ip`" clearable />
        </el-form-item>
        <el-form-item label="udid:">
            <el-input v-model="inputSearch.udid" :placeholder="`请输入udid`" clearable />
        </el-form-item>
        </el-form>
        <div class="search">
          <el-button type="primary" @click="onClickSearchAccount" :icon="Search">搜索</el-button>
        </div>
      </div>
  
      <!-- ------------表格--------------->
      <div class="table">
        <el-table v-loading="loading" :data="list" fit highlight-current-row style="width: 100%" :border="true">
          <el-table-column label="账号" align="center" prop="account" width="250px">
          </el-table-column>
          <el-table-column label="密码" align="center" prop="password" width="200px">
          </el-table-column>
          <el-table-column label="token" align="center" prop="token" width="290px">
          </el-table-column>
          <el-table-column label="phone" align="center" prop="phone" width="130px">
          </el-table-column>
          <el-table-column label="account_type" align="center" prop="account_type" width="130px">
          </el-table-column>
          <el-table-column label="status" align="center" prop="status" width="80px">
          </el-table-column>
          <el-table-column label="ip" align="center" prop="ip" width="110px">
          </el-table-column>
          <el-table-column label="nick_name" align="center" prop="nick_name" width="110px">
          </el-table-column>
          <el-table-column label="channel" align="center" prop="channel" width="110px">
          </el-table-column>
          <el-table-column label="os" align="center" prop="os" width="110px">
          </el-table-column>
          <el-table-column label="phone_type" align="center" prop="phone_type" width="110px">
          </el-table-column>
          <el-table-column label="udid" align="center" prop="udid" width="210px">
          </el-table-column>
          <el-table-column label="包名" align="center" prop="bundle_name" width="150px">
          </el-table-column>
          <el-table-column label="system_version" align="center" prop="system_version" width="150px">
          </el-table-column>
          <el-table-column label="create_time" align="center" prop="create_time" width="200px">
          </el-table-column>
          <el-table-column label="last_login_time" align="center" prop="last_login_time" width="200px">
          </el-table-column>
          <el-table-column label="sex" align="center" prop="sex" width="130px">
          </el-table-column>
          <el-table-column label="头像" width="90px" align="center">
            <template #default="scope">
              <el-avatar :size="80" :src="scope.row.headimgurl">
                <img src="" />
              </el-avatar>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- ------------分页--------------->
      <div class="pagination">
        <el-pagination v-model:currentPage="listQuery.pagenum" :page-size="listQuery.pagesize" background
          layout="total, sizes, prev, pager, next, jumper" :total="pageObj.total" @size-change="handleSizeChange"
          @current-change="getAccountList" />
      </div>

        </el-tab-pane>
        <el-tab-pane label="账号注册" name="second" >
            <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
          <div id="accountRegisterContainer" style="width: 80rem;height:50rem;" ref="registerChartsRef"></div>

        </el-tab-pane>
        <el-tab-pane label="账号登录" name="third">
          <div style="width: 80rem;height:50rem;" ref="loginChartsRef"></div>
        </el-tab-pane>
        <el-tab-pane label="留存" name="four">
            <el-date-picker
          v-model="searchTime"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
          <el-button type="primary" @click="getKeepList" style="margin-left:20px;margin-bottom:5px;" :icon="Search">搜索</el-button>
        
        
          

    <el-table v-loading="loading" :data="keepList" fit highlight-current-row style="width: 100%" :border="true">
    <el-table-column label="日期" align="center" prop="date" width="140px"> </el-table-column>
    <el-table-column label="注册" align="center" prop="registerNum" width="105px"> </el-table-column>
    <el-table-column label="次日留存" align="center" prop="keepuser2" width="105px"> </el-table-column>
    <el-table-column label="3日留存" align="center" prop="keepuser3" width="105px"> </el-table-column>
    <el-table-column label="5日留存" align="center" prop="keepuser5" width="105px"> </el-table-column>
    <el-table-column label="7日留存" align="center" prop="keepuser7" width="105px"> </el-table-column>
    <el-table-column label="10日留存" align="center" prop="keepuser10" width="105px"> </el-table-column>
    <el-table-column label="15日留存" align="center" prop="keepuser15" width="105px"> </el-table-column>
    <el-table-column label="30日留存" align="center" prop="keepuser30" width="105px"> </el-table-column>
    <el-table-column label="60日留存" align="center" prop="keepuser60" width="105px"> </el-table-column>
   
  </el-table>
        </el-tab-pane>
      </el-tabs>

  
    </div>
  </template>
  <script lang="ts" setup name="comprehensive">
  import * as echarts from 'echarts'
  import { EChartsType } from 'echarts/core'

  import { Search } from '@element-plus/icons-vue'
  import { computed, ref, reactive, onMounted, nextTick } from 'vue'
  import * as dayjs from 'dayjs'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { Logger } from '@/engine/util/Logger'
  import { HttpClient } from '@/utils/HttpClient'
  import { da, fa, fi, ro, tr } from 'element-plus/es/locale'
  import { UIHelper } from '@/utils/UIHelper'
  import { Config } from '@/config/Config'
  import { config } from 'exceljs'
  import { UserModel } from '@/store/model/UserModel'
  import { GameConfig } from '@/config/GameConfig'
  import { DateUtil } from '@/engine/util/DateUtil'
  const loading = ref(true)
  const appContainer = ref(null)
  
  const activeName = ref("first")

  let searchTime: Array<Date> =  reactive([
    new Date(),
    new Date(),
  ])


  let fileList = []
  
  const inputSearch = reactive({
    account: '',
    ip: '',
  })
  
  //列表查询选项
  const listQuery = reactive({
    pagenum: 1, //第几页
    pagesize: 100, //一页多少个
  })
  
  let list = reactive([
    {
    }
  ])
  let pageObj = reactive({
    total: 0
  })
  let keepList =  reactive([
    {
    }
  ])

  const registerChartsRef = ref<HTMLElement | null>()
  let registerChart: EChartsType
  let loginChart:EChartsType
  let loginChartsRef =  ref<HTMLElement | null>()
  const initRegisterChart = (keyList:Array<string>, valueList:Array<string>) => {
     // 基于准备好的dom，初始化echarts实例
    //  var myChart = echarts.init(document.getElementById('main'));
    registerChart = echarts.init(registerChartsRef.value)
    
      // 指定图表的配置项和数据
      let option = {
        title: {
          text: ''
        },
        tooltip: {},
        legend: {
          data: ['人数']
        },
        xAxis: {
          // data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
          data: keyList
        },
        yAxis: {},
        series: [
          {
            name: '人数',
            // type: 'line',
            type: 'bar',
            data: valueList,
          }
        ]
      };

      registerChart.setOption(option)
    return registerChart
  }

  function initLoginChart(keyList:Array<string>, valueList:Array<string>){
    loginChart = echarts.init(loginChartsRef.value)
    
    // 指定图表的配置项和数据
    let option = {
      title: {
        text: ''
      },
      tooltip: {},
      legend: {
        data: ['人数']
      },
      xAxis: {
        // data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
        data: keyList
      },
      yAxis: {},
      series: [
        {
          name: '人数',
          // type: 'line',
          type: 'bar',
          data: valueList,
        }
      ]
    };

    loginChart.setOption(option)
  return loginChart
  }
  
  
  onMounted(() => {
    let now: Date = new Date();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    let pre: Date = new Date(now.getTime() - Config.One_Day * 30);
    searchTime.splice(0)
    searchTime[0] = pre
    searchTime[1] = now


    nextTick(() => {
      // let data = appContainer.value.
    })
    setTimeout(() => {
      loading.value = false
    }, 500)
    getAccountList()
  })

  
const onClickTab = (tab, event) => {
  Logger.log("onClickTab===", tab, event)
  switch (tab.props.name) {
    case 'first':
    getAccountList()
      break;
    case 'second':
    get_account_register()
      break;
    case 'third':
    get_account_login()
      break;
    case "four":
      getKeepList()
    default:
      break;
  }
}
  
  const handleSizeChange = (val: number) => {
    listQuery.pagesize = val
    getAccountList()
  }
  
  const formatAccountList = (accounts: Array<object>) => {
    list.splice(0)
    for (let i = 0; i < accounts.length; i++) {
      let account = {
        "account": accounts[i]["account"],
        "password": accounts[i]["password"],
        "token": accounts[i]["token"],
        "account_type": accounts[i]["account_type"],
        "status": accounts[i]["status"],
        "ip": accounts[i]["ip"],
        "nick_name": accounts[i]["nick_name"],
        "channel": accounts[i]["channel"],
        "os": accounts[i]["os"],
        "phone_type": accounts[i]["phone_type"],
        "bundle_name": accounts[i]["bundle_name"],
        "system_version": accounts[i]["system_version"] ,
        "create_time":  DateUtil.formatDateStr(new Date(accounts[i]["create_time"]).getTime()),
        "last_login_time": DateUtil.formatDateStr(new Date(accounts[i]["last_login_time"]).getTime()),
        "phone": accounts[i]["phone"],
        "sex": accounts[i]["sex"],
        "headimgurl": accounts[i]["headimgurl"],
        "udid": accounts[i]["udid"],
      }
    
      list[i] = account
    }
  }
  
  const getAccountList = () => {
    loading.value = true;
    HttpClient.get_account_list(listQuery.pagenum, listQuery.pagesize, (data: object) => {
      loading.value = false
      let accounts: Array<object> = data["accounts"]
        formatAccountList(accounts)
      pageObj.total = data["count"]
      Logger.log("list", list)
      Logger.log("total", pageObj)
    })
  }

  const onClickSearchAccount = ()=>{
    let searchKey = ""
    let searchValue = ""
    if(inputSearch.account != ""){
      searchKey = "account"
      searchValue = inputSearch.account
    }
    else if(inputSearch.ip != ""){
      searchKey = "ip"
      searchValue = inputSearch.ip
    }
    else if(inputSearch.udid){
      searchKey = "udid"
      searchValue = inputSearch.udid
    }

    if(searchKey != ""){
      HttpClient.search_account(searchKey, searchValue, (accounts: Array<object> )=>{
        formatAccountList(accounts)
      })
    }else{
      getAccountList()
    }

  }

  function get_account_register() {
      HttpClient.get_account_register((dataList:Array<object>)=>{
        let keyList:Array<string> = []
          let valueList:Array<string> = []
          for(let i=0; i<dataList.length; i++){
            keyList[i] = dataList[i]["date"]
            valueList[i] = dataList[i]["count"]
          }
        initRegisterChart(keyList, valueList)
      })
  }

  function get_account_login() {
      HttpClient.get_account_login((dataList:Array<object>)=>{
        let keyList:Array<string> = []
          let valueList:Array<string> = []
          for(let i=0; i<dataList.length; i++){
            keyList[i] = dataList[i]["date"]
            valueList[i] = dataList[i]["count"]
          }
          initLoginChart(keyList, valueList)
      })
  }

  function getKeepList() {
    if (!searchTime || searchTime.length <= 0) {
      UIHelper.showMsg("请选择时间")
      return;
    }
    HttpClient.get_account_keep(
      searchTime,
      (result: Array<object>) => {
        formatKeepList(result)
      }
    );
  }

    
  function formatKeepList(dataList: Array<object>){
    keepList.splice(0)
    for (let i = 0; i < dataList.length; i++) {
      let data = {
        "date": dataList[i]["date"],
        "registerNum": dataList[i]["registerNum"],
        "keepuser2": dataList[i]["keepuser2"],
        "keepuser3": dataList[i]["keepuser3"],
        "keepuser5": dataList[i]["keepuser5"],
        "keepuser7": dataList[i]["keepuser7"],
        "keepuser10": dataList[i]["keepuser10"],
        "keepuser15": dataList[i]["keepuser15"],
        "keepuser30": dataList[i]["keepuser30"],
        "keepuser60": dataList[i]["keepuser60"],
      }
      keepList[i] = data
    }
  }
  
  </script>
    
  <style scoped lang="scss">
  .header {
    display: flex;
    padding: 16px 16px 0 16px;
    margin-bottom: 16px;
    border-radius: 4px;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
  
    .search-form {
      flex: 1;
  
      ::v-deep {
        .el-input--default {
          width: 200px;
        }
      }
    }
  
    .search {
      flex-shrink: 0;
      white-space: nowrap;
    }
  }
  </style>
    